package com.sync.syncmasterdata.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 认证工具类 使用业务中台的token
 */
@Service
@Slf4j
public class AuthUtil {

    @Value("${cloudpivotprops.url}")
    private String CPURL;

    @Autowired
    private RequestConfig config;

    @Autowired
    private CloseableHttpClient httpClient;

    /**
     * 使用tag标签获取cp缓存的token
     *
     * @param tag
     * @return
     * @throws Exception
     */
    public String getCPTokenByTag(String tag) {
        try {
            String url = String.format("%s/api/systemInteg/getTokenByAppTag?appTag=%s", CPURL, tag);
            // 声明 http get 请求
            HttpGet httpGet = new HttpGet(url);
            // 装载配置信息
            httpGet.setConfig(config);
            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpGet);
            // 判断状态码是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 返回响应体的内容
                JSONObject jsonObject = new JSONObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
                log.info("获取token", jsonObject.toString());
                if (jsonObject.getInt("code") == 1) {
                    return jsonObject.getString("msg");
                } else {
                    return null;
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
